package com.genshang.restaurant.util;

import com.alibaba.fastjson.JSON;
import com.genshang.restaurant.constant.ResultConstant;
import com.genshang.restaurant.result.CommonEnum;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

public class MiniProgramUtil {
    Logger logger = LoggerFactory.getLogger(MiniProgramUtil.class);

    static MiniProgramUtil miniProgramHandler = new MiniProgramUtil();

    public static MiniProgramUtil getMiniProgramHandler() {
        return miniProgramHandler;
    }

    private MiniProgramUtil() {
    }

    // 根据code获取openid登录
    private static String BASE_REQUEST_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    private static String REQUEST_PREPAY_ID_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    private static String TRADE_TYPE = "JSAPI";

    private static String SPBILL_CREATE_IP = "127.0.0.1";


    public Map<String, Object> requestWXLogin(String code, String appid, String secret) {
        logger.info("调用微信服务器登录API");
        Map<String, Object> requestResultMap = new HashMap<>();
        StringBuilder requestStringBuilder = new StringBuilder(BASE_REQUEST_LOGIN_URL)
                .append("?appid=").append(appid)
                .append("&secret=").append(secret)
                .append("&grant_type=authorization_code&js_code=").append(code);
        String requestUrl = requestStringBuilder.toString();
        try {
            String responseString = HttpUtil.get(requestUrl);
            logger.info(responseString);
            requestResultMap = JSON.parseObject(responseString, Map.class);
            return requestResultMap;
        } catch (Exception e) {
            e.printStackTrace();
            requestResultMap.put(ResultConstant.ERROR_CODE, CommonEnum.INTERNAL_SERVER_ERROR.getResultCode());
            requestResultMap.put(ResultConstant.ERROR_MESSAGE, CommonEnum.INTERNAL_SERVER_ERROR.getResultMsg());
        }
        return requestResultMap;
    }

    /**
     * @param appid        小程序ID
     * @param mch_id       商户号
     * @param body         商品描述
     * @param out_trade_no 商户订单号
     * @param total_fee    标价金额
     * @param notify_url   通知地址
     * @param wechatKey    微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
     * @return
     * @link https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=4_3
     * https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1&index=1
     */
    public Map<String, String> unifiedOrder(String appid, String notify_url, String out_trade_no,
                                            String body, String total_fee, String mch_id, String wechatKey, String openid) {


        String notify = notify_url + out_trade_no + "/wx";
        //生成的随机字符串
        String nonce_str = getRandomStringByLength(32);
        //获取客户端的ip地址account
        String ipAddress = SPBILL_CREATE_IP;
        logger.info("ip地址:" + ipAddress);

        //转换为分单位
        BigDecimal reqMoney = new BigDecimal(total_fee);
        BigDecimal parseMoney = reqMoney.multiply(new BigDecimal(100));
        parseMoney = parseMoney.setScale(0, RoundingMode.UP);
        total_fee = parseMoney.toString();

        //组装参数，用户生成统一下单接口的签名
        Map<String, String> packageParamMap = new HashMap<>();
        packageParamMap.put("appid", appid);
        packageParamMap.put("mch_id", mch_id);
        packageParamMap.put("nonce_str", nonce_str);
        packageParamMap.put("body", body);  //商品描述
        packageParamMap.put("out_trade_no", out_trade_no);//商户订单号
        packageParamMap.put("total_fee", total_fee);//支付金额，这边需要转成字符串类型，否则后面的签名会失败
        packageParamMap.put("spbill_create_ip", ipAddress);
        packageParamMap.put("notify_url", notify);//支付成功后的回调地址
        packageParamMap.put("trade_type", TRADE_TYPE);//支付方式
        packageParamMap.put("openid", openid);

        String preString = createLinkString(packageParamMap); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口
        String mySign = sign(preString, wechatKey, "utf-8").toUpperCase();
        //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去
        String xml = "<xml>" + "<appid>" + appid + "</appid>"
                + "<body><![CDATA[" + body + "]]></body>"
                + "<mch_id>" + mch_id + "</mch_id>"
                + "<nonce_str>" + nonce_str + "</nonce_str>"
                + "<notify_url>" + notify + "</notify_url>"
                + "<openid>" + openid + "</openid>"
                + "<out_trade_no>" + out_trade_no + "</out_trade_no>"
                + "<spbill_create_ip>" + ipAddress + "</spbill_create_ip>"
                + "<total_fee>" + total_fee + "</total_fee>"
                + "<trade_type>" + TRADE_TYPE + "</trade_type>"
                + "<sign>" + mySign + "</sign>"
                + "</xml>";
        Map<String, String> responseMap = new HashMap<>();//返回给小程序端需要的参数
        try {
            String result = HttpUtil.post(String.format(REQUEST_PREPAY_ID_URL), xml);
            System.out.println("result = " + result);
            // 将解析结果存储在HashMap中
            Map map = doXMLParse(result);
            String resultCode = map.get("result_code").toString();//返回状态码
            if (resultCode.equals("SUCCESS")) {
                String prepay_id = (String) map.get("prepay_id");//返回的预付单信息
                String timeStamp = System.currentTimeMillis() / 1000 + "";
                //拼接签名需要的参数
                String stringSignTemp = "appId=" + appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
                //再次签名，这个签名用于小程序端调用wx.requesetPayment方法
                String paySign = sign(stringSignTemp, wechatKey, "utf-8").toUpperCase();
                responseMap.put("appId", appid);
                responseMap.put("timeStamp", timeStamp);
                responseMap.put("nonceStr", nonce_str);
                responseMap.put("package", "prepay_id=" + prepay_id);
                responseMap.put("signType", "MD5");
                responseMap.put("paySign", paySign);
                responseMap.put("SUCCESS", "1");
            } else {
                responseMap.put("SUCCESS", "0");
                responseMap.put("MESSAGE", map.get("err_code_des").toString());
            }
            return responseMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        responseMap.put("SUCCESS", "0");
        return responseMap;
    }


    /**
     * 签名字符串
     *
     * @param text          需要签名的字符串
     * @param key           密钥
     * @param input_charset 编码格式
     * @return 签名结果
     */
    private String sign(String text, String key, String input_charset) {
        text = text + "&key=" + key;
        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }

    /**
     * @param content
     * @param charset
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    private String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }

    /**
     * 获取一定长度的随机字符串，范围0-9，a-z
     *
     * @param length：指定字符串长度
     * @return 一定长度的随机字符串
     */
    private String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获取真实的ip地址
     *
     * @param request
     * @return
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

    public static InputStream String2Inputstream(String str) {
        return new ByteArrayInputStream(str.getBytes());
    }

    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
     *
     * @param strxml
     * @return
     * @throws
     */
    private Map doXMLParse(String strxml) throws Exception {
        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        Map m = new HashMap();
        InputStream in = String2Inputstream(strxml);
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }

        //关闭流
        in.close();

        return m;
    }

    /**
     * 获取子结点的xml
     *
     * @param children
     * @return String
     */
    private String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }
}
